package com.kamfu.bio.server;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * @program: kamfu
 * @ClassName BioServer1
 * @description:多客户端实现
 * @author: liandy
 * @create: 2021-12-30 10:23
 * @Version 1.0
 **/
public class BioMultipleThreadServer {
    public static void main(String[] args) {
        try {
            //1.建立ServerSocket监听本地端口
            ServerSocket serverSocket=new ServerSocket(9000);
            while (true){
                //2.等待客户端连接，程序将处于阻塞状态
                Socket socket = serverSocket.accept();
                System.out.println("新的客户端连接成功");
                //开启线程处理socket
                new Thread(new SocketThread(socket)).start();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

class SocketThread implements Runnable{
    private Socket socket;
    public SocketThread(Socket socket){
        this.socket=socket;
    }
    @Override
    public void run() {
        try {
            //3.获取输入流
            InputStream inputStream = socket.getInputStream();
            //4.将字节流包装成字符流
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
            //5.创建字符缓冲区
            BufferedReader bufferedReader=new BufferedReader(inputStreamReader);
            String message;
            //6.阻塞等待客户端发送消息,直到读取到换行符
            while((message=bufferedReader.readLine())!=null){
                System.out.println("服务端接收到消息："+message);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}